<template>
  <Head title="申请售后服务" />
  <ShopLayout>
    <div class="bg-gray-100 min-h-screen">
      <div class="max-w-7xl mx-auto px-8 sm:px-16 lg:px-24 py-20">
        <!-- 页面标题 -->
        <div class="mb-8">
          <div class="flex items-center space-x-4">
            <Link 
              :href="route('after-sales.index')"
              class="text-gray-600 hover:text-gray-900"
            >
              <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
              </svg>
            </Link>
            <div>
              <h1 class="text-3xl font-light text-gray-900">申请售后服务</h1>
              <p class="mt-2 text-gray-600">请填写售后申请信息</p>
            </div>
          </div>
        </div>

        <!-- 审核说明 -->
        <div class="bg-blue-50 rounded-2xl p-6">
          <div class="flex items-start">
            <div class="flex-shrink-0">
              <svg class="h-6 w-6 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <div class="ml-3">
              <h3 class="text-lg font-medium text-blue-900">审核说明</h3>
              <div class="mt-2 text-sm text-blue-800">
                <p>所有售后申请都需要后台审核，我们会在1-2个工作日内处理您的申请：</p>
                <ul class="mt-2 list-disc list-inside space-y-1">
                  <li><strong>退货/退款</strong>：审核通过后，我们会联系您安排后续流程</li>
                  <li><strong>换货</strong>：审核通过后，您会收到通知，此时可以填写寄回物流信息</li>
                </ul>
              </div>
            </div>
          </div>
        </div>

        <form @submit.prevent="submitForm" class="space-y-6">
          <!-- 订单信息 -->
          <div v-if="order" class="bg-white rounded-2xl p-8 shadow-sm">
            <h2 class="text-2xl font-light text-gray-900 mb-6">订单信息</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">订单号</label>
                <p class="text-lg text-gray-900">{{ order.order_number }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">订单状态</label>
                <p class="text-lg text-gray-900">{{ getOrderStatusText(order.status) }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">订单金额</label>
                <p class="text-lg text-gray-900">¥{{ order.total_amount }}</p>
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">下单时间</label>
                <p class="text-lg text-gray-900">{{ formatDate(order.created_at) }}</p>
              </div>
            </div>
          </div>

          <!-- 售后类型和原因 -->
          <div class="bg-white rounded-2xl p-8 shadow-sm">
            <h2 class="text-2xl font-light text-gray-900 mb-6">售后信息</h2>
            
            <div class="space-y-6">
              <!-- 售后类型 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-4">售后类型 *</label>
                <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
                  <div 
                    v-for="type in afterSalesTypes" 
                    :key="type.value"
                    @click="form.type = type.value"
                    class="relative border-2 rounded-2xl p-6 cursor-pointer transition-all"
                    :class="form.type === type.value ? 'border-gray-900 bg-gray-50' : 'border-gray-200 hover:border-gray-300'"
                  >
                    <div class="text-center">
                      <div class="text-3xl mb-3">{{ type.icon }}</div>
                      <div class="text-lg font-medium text-gray-900">{{ type.label }}</div>
                      <div class="text-sm text-gray-500 mt-1">{{ type.description }}</div>
                    </div>
                    <div
                      v-if="form.type === type.value"
                      class="absolute top-4 right-4"
                    >
                      <svg class="w-6 h-6 text-gray-900" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
                      </svg>
                    </div>
                  </div>
                </div>
                <div v-if="errors.type" class="mt-2 text-sm text-red-600">{{ errors.type }}</div>
              </div>

              <!-- 申请原因 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">申请原因 *</label>
                <select 
                  v-model="form.reason"
                  class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                >
                  <option value="">请选择申请原因</option>
                  <option value="质量问题">质量问题</option>
                  <option value="商品与描述不符">商品与描述不符</option>
                  <option value="发错商品">发错商品</option>
                  <option value="商品损坏">商品损坏</option>
                  <option value="尺寸不合适">尺寸不合适</option>
                  <option value="颜色不喜欢">颜色不喜欢</option>
                  <option value="其他原因">其他原因</option>
                </select>
                <div v-if="errors.reason" class="mt-2 text-sm text-red-600">{{ errors.reason }}</div>
              </div>

              <!-- 整体情况说明 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                  整体情况说明
                  <span class="text-gray-500 text-sm font-normal">(可选)</span>
                </label>
                <textarea 
                  v-model="form.description"
                  rows="3"
                  placeholder="请描述整体情况，如：包裹损坏、配送问题、对本次购物体验不满意等（可选）"
                  class="w-full px-4 py-3 border border-gray-300 rounded-2xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900 resize-none"
                ></textarea>
                <p class="text-xs text-gray-500 mt-2">如果只是单个商品的问题，可以跳过此步骤</p>
                <div v-if="errors.description" class="mt-2 text-sm text-red-600">{{ errors.description }}</div>
              </div>

              <!-- 换货流程说明 -->
              <div v-if="form.type === 'exchange'" class="border-t border-gray-200 pt-6">
                <div class="bg-blue-50 rounded-2xl p-6">
                  <h3 class="text-lg font-medium text-blue-900 mb-4 flex items-center">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    换货流程说明
                  </h3>
                  <div class="space-y-3 text-sm text-blue-800">
                    <div class="flex items-start">
                      <span class="flex-shrink-0 w-6 h-6 bg-blue-200 rounded-full flex items-center justify-center text-xs font-medium text-blue-800 mr-3 mt-0.5">1</span>
                      <p>提交换货申请后，我们会在1-2个工作日内审核</p>
                    </div>
                    <div class="flex items-start">
                      <span class="flex-shrink-0 w-6 h-6 bg-blue-200 rounded-full flex items-center justify-center text-xs font-medium text-blue-800 mr-3 mt-0.5">2</span>
                      <p>审核通过后，您会收到通知，此时可以填写寄回物流信息</p>
                    </div>
                    <div class="flex items-start">
                      <span class="flex-shrink-0 w-6 h-6 bg-blue-200 rounded-full flex items-center justify-center text-xs font-medium text-blue-800 mr-3 mt-0.5">3</span>
                      <p>我们收到商品并确认无误后，会立即寄出新的商品</p>
                    </div>
                    <div class="flex items-start">
                      <span class="flex-shrink-0 w-6 h-6 bg-blue-200 rounded-full flex items-center justify-center text-xs font-medium text-blue-800 mr-3 mt-0.5">4</span>
                      <p>新商品发出后，您会收到物流跟踪信息</p>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 退款流程说明 -->
              <div v-if="form.type === 'refund'" class="border-t border-gray-200 pt-6">
                <div class="bg-green-50 rounded-2xl p-6">
                  <h3 class="text-lg font-medium text-green-900 mb-4 flex items-center">
                    <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1" />
                    </svg>
                    退款流程说明
                  </h3>
                  <div class="space-y-3 text-sm text-green-800">
                    <div class="flex items-start">
                      <span class="flex-shrink-0 w-6 h-6 bg-green-200 rounded-full flex items-center justify-center text-xs font-medium text-green-800 mr-3 mt-0.5">1</span>
                      <p>提交退款申请后，我们会在1-2个工作日内审核</p>
                    </div>
                    <div class="flex items-start">
                      <span class="flex-shrink-0 w-6 h-6 bg-green-200 rounded-full flex items-center justify-center text-xs font-medium text-green-800 mr-3 mt-0.5">2</span>
                      <p>审核通过后，我们会立即处理退款</p>
                    </div>
                    <div class="flex items-start">
                      <span class="flex-shrink-0 w-6 h-6 bg-green-200 rounded-full flex items-center justify-center text-xs font-medium text-green-800 mr-3 mt-0.5">3</span>
                      <p>退款将在3-7个工作日内原路返回到您的支付账户</p>
                    </div>
                  </div>
                </div>
              </div>


              <!-- 图片上传 -->
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">上传凭证图片</label>
                <p class="text-sm text-gray-500 mb-4">最多上传5张图片，支持 jpg、png、gif 格式，单张图片不超过2MB</p>
                
                <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">
                  <!-- 已上传的图片 -->
                  <div 
                    v-for="(image, index) in uploadedImages" 
                    :key="index"
                    class="relative group"
                  >
                    <img 
                      :src="image.preview" 
                      :alt="`凭证图片 ${index + 1}`"
                      class="h-24 w-full object-cover rounded-2xl border border-gray-300"
                    >
                    <button 
                      @click="removeImage(index)"
                      type="button"
                      class="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                      </svg>
                    </button>
                  </div>
                  
                  <!-- 上传按钮 -->
                  <div 
                    v-if="uploadedImages.length < 5"
                    class="flex items-center justify-center h-24 border-2 border-dashed border-gray-300 rounded-2xl hover:border-gray-900 transition-colors cursor-pointer"
                    @click="triggerFileUpload"
                  >
                    <div class="text-center">
                      <svg class="mx-auto h-8 w-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                      </svg>
                      <p class="text-xs text-gray-500 mt-1">上传图片</p>
                    </div>
                  </div>
                </div>
                
                <input 
                  ref="fileInput"
                  type="file"
                  multiple
                  accept="image/*"
                  @change="handleFileUpload"
                  class="hidden"
                >
                <div v-if="errors.images" class="mt-2 text-sm text-red-600">{{ errors.images }}</div>
              </div>
            </div>
          </div>

          <!-- 售后商品选择 -->
          <div v-if="order" class="bg-white rounded-2xl p-8 shadow-sm">
            <h2 class="text-2xl font-light text-gray-900 mb-6">选择售后商品 *</h2>
            
            <!-- 填写说明 -->
            <div class="bg-blue-50 rounded-2xl p-4 mb-6">
              <div class="flex items-start">
                <svg class="h-5 w-5 text-blue-500 mt-0.5 mr-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <div class="text-sm text-blue-800">
                  <p class="font-medium mb-1">填写说明：</p>
                  <p class="text-blue-700">请在上方详细说明您遇到的问题，我们将根据您的描述处理售后申请</p>
                </div>
              </div>
            </div>
            
            <div class="space-y-4">
              <div 
                v-for="item in order.items" 
                :key="item.id"
                class="border border-gray-200 rounded-2xl p-6"
              >
                <div class="flex items-start space-x-4">
                  <img 
                    :src="item.product.image || '/images/product-placeholder.svg'"
                    :alt="item.product.name"
                    class="h-20 w-20 rounded-2xl object-cover"
                  >
                  
                  <div class="flex-1">
                    <h3 class="text-lg font-medium text-gray-900">{{ item.product.name }}</h3>
                    <p v-if="item.variant" class="text-sm text-gray-500 mt-1">
                      规格：{{ item.variant.name }}
                    </p>
                    <p class="text-sm text-gray-500 mt-1">
                      单价：¥{{ item.price }} | 购买数量：{{ item.quantity }}
                    </p>
                  </div>
                  
                  <div class="flex items-center space-x-4">
                    <div>
                      <label class="block text-sm font-medium text-gray-700 mb-2">售后数量</label>
                      <input 
                        type="number"
                        :min="1"
                        :max="item.quantity"
                        :value="form.items[item.id]?.quantity || 1"
                        @input="updateItemQuantity(item.id, $event.target.value)"
                        class="w-20 px-3 py-2 border border-gray-300 rounded-xl shadow-sm focus:ring-2 focus:ring-gray-900 focus:border-gray-900"
                      >
                    </div>
                    
                    <div class="flex items-center">
                      <input 
                        type="checkbox"
                        :id="`item-${item.id}`"
                        :checked="form.items[item.id]?.selected || false"
                        @change="updateItemSelected(item.id, $event.target.checked)"
                        class="h-5 w-5 text-gray-900 focus:ring-gray-900 border-gray-300 rounded"
                      >
                      <label :for="`item-${item.id}`" class="ml-3 text-sm font-medium text-gray-700">
                        选择此商品
                      </label>
                    </div>
                  </div>
                </div>
                
              </div>
            </div>
            
            <div v-if="errors.items" class="mt-4 text-sm text-red-600">{{ errors.items }}</div>
          </div>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-4">
            <Link 
              :href="route('after-sales.index')"
              class="px-8 py-3 border border-gray-300 rounded-2xl text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900"
            >
              取消
            </Link>
            <button 
              type="submit"
              :disabled="isSubmitting"
              class="px-8 py-3 border border-transparent rounded-2xl shadow-sm text-sm font-medium text-white bg-gray-900 hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <span v-if="isSubmitting">提交中...</span>
              <span v-else>提交申请</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  </ShopLayout>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { Head, Link, router, useForm } from '@inertiajs/vue3'
import ShopLayout from '@/Layouts/ShopLayout.vue'
import { useNotification } from '@/composables/useNotification'

const { showError, showSuccess } = useNotification()

const props = defineProps({
  order: Object,
  errors: Object,
  logisticsCompanies: {
    type: Array,
    default: () => []
  }
})

const fileInput = ref(null)
const uploadedImages = ref([])
const isSubmitting = ref(false)

const afterSalesTypes = [
  { value: 'return', label: '退货', description: '退回商品，申请退款（需审核）', icon: '📦' },
  { value: 'refund', label: '退款', description: '仅申请退款，不退回商品（需审核）', icon: '💰' },
  { value: 'exchange', label: '换货', description: '更换其他商品（需审核）', icon: '🔄' }
]

const form = useForm({
  order_id: props.order?.id || null,
  type: '',
  reason: '',
  description: '',
  images: [],
  items: {},
  logistics: {
    company: '',
    tracking_number: '',
    sender_name: '',
    sender_phone: '',
    sender_address: '',
    note: ''
  }
})

// 初始化商品选择
onMounted(() => {
  if (props.order) {
    props.order.items.forEach(item => {
      form.items[item.id] = {
        selected: false,
        quantity: 1
      }
    })
  }
})

const selectedItems = computed(() => {
  return Object.entries(form.items)
    .filter(([itemId, itemData]) => itemData && itemData.selected)
    .map(([itemId, itemData]) => ({
      order_item_id: parseInt(itemId),
      quantity: itemData.quantity || 1
    }))
})

const updateItemQuantity = (itemId, value) => {
  if (!form.items[itemId]) {
    form.items[itemId] = {
      selected: false,
      quantity: 1
    }
  }
  form.items[itemId].quantity = parseInt(value) || 1
}

const updateItemSelected = (itemId, selected) => {
  if (!form.items[itemId]) {
    form.items[itemId] = {
      selected: false,
      quantity: 1
    }
  }
  form.items[itemId].selected = selected
}

const triggerFileUpload = () => {
  fileInput.value.click()
}

const handleFileUpload = (event) => {
  const files = Array.from(event.target.files)
  
  files.forEach(file => {
    if (uploadedImages.value.length >= 5) return
    
    // 验证文件类型和大小
    if (!file.type.startsWith('image/')) {
      showError('文件类型错误', '请选择图片文件')
      return
    }
    
    if (file.size > 2 * 1024 * 1024) {
      showError('文件过大', '图片大小不能超过2MB')
      return
    }
    
    // 创建预览
    const reader = new FileReader()
    reader.onload = (e) => {
      uploadedImages.value.push({
        file: file,
        preview: e.target.result
      })
    }
    reader.readAsDataURL(file)
  })
  
  // 清空input
  event.target.value = ''
}

const removeImage = (index) => {
  uploadedImages.value.splice(index, 1)
}

const submitForm = () => {
  // 验证表单
  if (!form.type) {
    showError('表单验证失败', '请选择售后类型')
    return
  }
  
  if (!form.reason) {
    showError('表单验证失败', '请选择申请原因')
    return
  }
  
  if (selectedItems.value.length === 0) {
    showError('表单验证失败', '请至少选择一个商品进行售后')
    return
  }
  
  // 验证选中的商品（商品状态和具体原因字段已删除，不再需要验证）
  
  
  // 准备提交数据
  const submitData = {
    order_id: form.order_id,
    type: form.type,
    reason: form.reason,
    description: form.description,
    items: selectedItems.value
  }
  
  // 处理图片上传
  if (uploadedImages.value.length > 0) {
    const formData = new FormData()
    
    // 添加表单数据
    Object.keys(submitData).forEach(key => {
      if (key === 'items') {
        // 将items数组的每个元素分别添加到FormData
        submitData[key].forEach((item, index) => {
          Object.keys(item).forEach(itemKey => {
            formData.append(`items[${index}][${itemKey}]`, item[itemKey])
          })
        })
      } else {
        formData.append(key, submitData[key])
      }
    })
    
    // 添加图片
    uploadedImages.value.forEach((image, index) => {
      formData.append(`images[${index}]`, image.file)
    })
    
    isSubmitting.value = true
    
    router.post(route('after-sales.store'), formData, {
      forceFormData: true,
      onSuccess: () => {
        isSubmitting.value = false
        showSuccess('售后申请已提交', '请等待审核')
      },
      onError: (errors) => {
        isSubmitting.value = false
        console.error('售后申请提交失败:', errors)
        showError('提交失败', '请检查表单信息后重试')
      }
    })
  } else {
    isSubmitting.value = true
    
    router.post(route('after-sales.store'), submitData, {
      onSuccess: () => {
        isSubmitting.value = false
        showSuccess('售后申请已提交', '请等待审核')
      },
      onError: (errors) => {
        isSubmitting.value = false
        console.error('售后申请提交失败:', errors)
        showError('提交失败', '请检查表单信息后重试')
      }
    })
  }
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

const getOrderStatusText = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    shipped: '已发货',
    delivered: '已送达',
    cancelled: '已取消'
  }
  return statusMap[status] || status
}
</script>
